#!/usr/bin/python3
# -*- coding:utf-8 -*-
# @Time   :2021/1/26
# @Author :CJX
# @File   :program_opening_and_protection.py

import os
import re
import signal
import time
import pymysql


# execute command, and return the information. 执行命令并返回命令输出信息
def execCmd(cmd):
    r = os.popen(cmd)
    text = r.read()
    r.close()
    return text


def doSomething():
    os.system('nohup python3 /home/pi/ph/watchdog.py >/dev/null  2>&1 &')


def stopi2c():
    processInfo = os.popen("ps -ef|grep watchdog.py|grep -v grep|awk '{print $2}'").readlines()
    for pid in processInfo:
        os.kill(int(pid), signal.SIGKILL)


# stop parent
def stopi2cParent():
    parentList = os.popen("ps -ef|grep watchdog.py|grep -v grep|awk '{print $2}'").readlines()
    for pid in parentList:
        os.kill(int(pid), signal.SIGKILL)


def stopAll():
    stopi2c()
    stopi2cParent()


if __name__ == '__main__':
    # ps -ef是linux查看进程信息指令，|是管道符号导向到grep去查找特定的进程,最后一个|是导向grep过滤掉grep进程：因为grep查看程序名也是进程，会混到查询信息里
    programIsRunningCmd = "ps -ef|grep watchdog.py|grep -v grep"
    programIsRunningCmdAns = execCmd(programIsRunningCmd)  # 调用函数执行指令，并返回指令查询出的信息
    ansLine = programIsRunningCmdAns.split('\n')  # 将查出的信息用换行符‘\b’分开
    # 判断如果返回行数>2则说明python脚本程序已经在运行，打印提示信息结束程序，否则运行脚本代码doSomething()
    if len(ansLine) == 2:
        print("programName have been Running")
    #        con = pymysql.connect(
    #            host='localhost',
    #            port=3306,
    #            user='root',
    #            password='!qAz2WsX3edc',
    #            db='ph',
    #            charset='utf8'
    #        )
    #        cur = con.cursor()
    #        min_id = cur.execute("SELECT min(id) FROM DHT20 ")
    #        min_id = int(cur.fetchone()[0])
    #        max_id = cur.execute("SELECT max(id) FROM DHT20 ")
    #        max_id = int(cur.fetchone()[0])
    #        if (max_id - min_id) >= 5000:
    #            sql2 = ("delete FROM DHT20 " + "WHERE id <= %s " % (max_id-1000) + " and id >= %s" % min_id)
    #            cur.execute(sql2)
    #        con.commit()
    #        cur.close()
    else:
        stopAll()
        print("寄")
        #        con = pymysql.connect(
        #            host='localhost',
        #            port=3306,
        #            user='root',
        #            password='!qAz2WsX3edc',
        #            db='ph',
        #            charset='utf8'
        #        )
        #        cur = con.cursor()
        #        restart = "FF"
        #        time1 = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
        #        cur.executemany(
        #            "INSERT restart_number(restart,time) VALUE(%s,%s)",
        #            [(restart, time1)])
        #        con.commit()
        #        cur.close()
        doSomething()
